# This class is a rewrite of PsitionSlider from Kaffeine project to Ruby
# Thanks guys!:D Hope You guys are not angry :)


class PositionSlider < Qt::Slider

	attr_reader :userChange

	slots 'onSliderPressed()', 'onSliderReleased()'

	signals 'startSeeking()', 'stopSeeking()'

	def initialize(orientation, parent = nil, name = nil)
		super(orientation, parent, name)
		connect(self, SIGNAL('sliderPressed()'), SLOT('onSliderPressed()'))
		connect(self, SIGNAL('sliderReleased()'), SLOT('onSliderReleased()'))
		installEventFilter(self)
		setFocusPolicy(Qt::Widget::NoFocus)
		@userChange = false
	end

	def setPosition(val, changePosition)
		if !@userChange
			setValue(val)
		end

		if changePosition
			setValue(val)
			emit sliderMoved(val)
		end
	end

	def onSliderPressed
		@userChange = true
		emit startSeeking()
	end

	def onSliderReleased
		emit stopSeeking()
		emit sliderMoved(value)
		@userChange = false
	end

	def wheelEvent(event)
		offset = log10(event.delta.abs)/0.002
		newVal = 0
		newVal = event.delta > 0 ? value + offset.to_i : value - offset.to_i
		newVal = newVal < 0 ? 0 : newVal
		setPosition(newVal, true)
		event.accept
	end

	def eventFilter(obj, event)
		if obj == self && (event.type == Qt::Event::MouseButtonPress ||
				   event.type == Qt::Event::MouseButtonDblClick)
			srect = sliderRect
			if srect.contains(event.pos) || event.button != Qt::LeftButton
				return false
			end

			range = maxValue - minValue
			pos = orientation == Qt::Horizontal ? event.pos.x : event.pos.y
			maxpos = orientation == Qt::Horizontal ? width : height
			value = pos * range / maxpos + minValue

			if Qt::Application.reverseLayout
				value = maxValue - (value - minValue)
			end

			setPosition(value, true)
			return true
		else
			return false
		end
	end
end
